package com.lucas.servlet.chapter3_3.controller;

import com.lucas.servlet.chapter3_3.entity.User;
import com.lucas.servlet.chapter3_3.service.LoginService;
import com.lucas.servlet.chapter3_3.service.UserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

//在Chapter33Appliation中运行会出现tomcat运行的端口号，浏览器打开即可
@Slf4j
@Controller   //使其成为类处理器
public class IndexController {
    //访问项目主页
    @RequestMapping(value = {"/index"})  //类似于servlet中的@webservlet
    public String index() {
        log.info("访问主页");
        return "index";   //请求转发
    }

    @RequestMapping(value = "/login",method = RequestMethod.GET)
    public String login(ModelAndView modelAndView) {
        log.info("访问登陆页面");
        modelAndView.setViewName("forward:/login");
        return "login";
    }

    @Autowired
    LoginService loginService;

    //登陆验证,注意参数是name，不是username，还有提交表单的时候也要改
    @RequestMapping(value = "/login", method = RequestMethod.POST, params = {"name", "password"})

//    @ResponseBody
    public ModelAndView userlogin(ModelAndView mv, User user) {
        log.info("" + user);
        log.info("正在进行登陆验证");
        if (loginService.login(user.getName(), user.getPassword())) {
            mv.setViewName("index");  //返回用户信息
            mv.addObject("user",user);
        } else {
            mv.setViewName("login");
            mv.addObject("error","登陆失败");
        }
        return mv;
    }

    //十二次课
    //接受访问注册界面的请求，并返回注册页面
    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public ModelAndView showregister(ModelAndView modelAndView) {
        modelAndView.setViewName("register");
        //添加实体类对象数据
        modelAndView.addObject("user", new User());
        return modelAndView;
    }

    @Autowired
    UserService userService;

    @RequestMapping(value = "/register", method = RequestMethod.POST)
    public ModelAndView handleregister(ModelAndView mv, User user) {
        //处理注册请求，待办事项
        try{
            userService.registerUser(user);
            mv.addObject("success","注册成功");
        } catch (Exception e) {
            log.error(e.getMessage());
            mv.addObject("error","注册失败");
        }
        return mv;
    }
}